<template>
    <Layout>
      <div class="attribute-container">
        <!-- 功能入口区域 -->
        <div class="function-area">
          <el-button type="primary" @click="handleCreateAttribute">新建商品属性</el-button>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入内容"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
  
        <!-- 数据列表 -->
        <div class="data-table">
          <el-table
            :data="attributeList"
            style="width: 100%"
            v-loading="loading"
            border
          >
            <el-table-column prop="name" label="属性名称" width="180" />
            <el-table-column prop="value" label="属性值" width="300">
              <template #default="scope">
                <el-tag
                  v-for="(value, index) in (scope.row.values || '').split(';')"
                  :key="index"
                  class="attribute-tag"
                  :type="getTagType(index)"
                >
                  {{ value }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="100" />
            <el-table-column prop="createdAt" label="创建时间" width="180" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
  
          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
  
        <!-- 新建/编辑属性弹窗 -->
        <el-dialog
          v-model="dialogVisible"
          :title="isEdit ? '编辑商品属性' : '新增商品属性'"
          width="500px"
          center
        >
          <el-form
            ref="formRef"
            :model="attributeForm"
            :rules="formRules"
            label-width="100px"
          >
            <el-form-item label="属性名称" prop="name">
              <el-input v-model="attributeForm.name" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="attributeForm.sort" :min="1" :max="999" />
            </el-form-item>
            <el-form-item label="属性值" prop="values">
              <el-tag
                v-for="(tag, index) in attributeForm.valueArray"
                :key="index"
                closable
                :disable-transitions="false"
                @close="handleCloseTag(index)"
                class="attribute-tag"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="inputRef"
                v-model="inputValue"
                class="tag-input"
                size="small"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button v-else class="button-new-tag" size="small" @click="showInput">
                + 添加属性值
              </el-button>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </Layout>
  </template>
  
  <style scoped>
  .attribute-container {
    padding: 0;
  }
  
  .function-area {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  
  .search-box {
    width: 300px;
  }
  
  .data-table {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .attribute-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }
  
  .tag-input {
    width: 100px;
    margin-right: 8px;
    vertical-align: bottom;
  }
  
  .button-new-tag {
    margin-bottom: 8px;
  }
  </style>
  
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import Layout from '@/components/Layout.vue';
import { getAttributeList, createAttribute, updateAttribute, deleteAttribute } from '@/api/attribute';

// 加载状态
const loading = ref(false);

// 属性列表数据
const attributeList = ref<any[]>([]);
const total = ref(0);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索关键字
const searchKeyword = ref('');

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();

// 标签输入相关
const inputVisible = ref(false);
const inputValue = ref('');
const inputRef = ref();

// 属性表单
const attributeForm = reactive({
  objectId: '',
  name: '',
  sort: 1,
  values: '',
  valueArray: [] as string[]
});

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入属性名称', trigger: 'blur' },
    { max: 50, message: '属性名称不能超过50个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
};

// 获取标签类型
const getTagType = (index: number) => {
  const types = ['', 'success', 'warning', 'danger', 'info'];
  return types[index % types.length];
};

// 加载属性列表
const loadAttributeList = async () => {
  loading.value = true;
  try {
    const response: any = await getAttributeList();
    attributeList.value = response.results || [];
    total.value = attributeList.value.length;
  } catch (error) {
    console.error('获取属性列表失败:', error);
    ElMessage.error('获取属性列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadAttributeList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadAttributeList();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadAttributeList();
};

// 处理新建属性
const handleCreateAttribute = () => {
  isEdit.value = false;
  dialogVisible.value = true;
  resetForm();
};

// 处理编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  resetForm();
  
  // 填充表单数据
  attributeForm.objectId = row.objectId;
  attributeForm.name = row.name;
  attributeForm.sort = row.sort || 1;
  attributeForm.values = row.values || '';
  attributeForm.valueArray = row.values ? row.values.split(';') : [];
  
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该属性吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAttribute(row.objectId);
      ElMessage.success('删除成功');
      loadAttributeList();
    } catch (error) {
      console.error('删除属性失败:', error);
      ElMessage.error('删除属性失败');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  attributeForm.objectId = '';
  attributeForm.name = '';
  attributeForm.sort = 1;
  attributeForm.values = '';
  attributeForm.valueArray = [];
  
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 将valueArray转换为分号分隔的字符串
        attributeForm.values = attributeForm.valueArray.join(';');
        
        // 构建提交数据
        const data = {
          name: attributeForm.name,
          values: attributeForm.values,
          sort: attributeForm.sort
        };
        
        if (isEdit.value) {
          await updateAttribute(attributeForm.objectId, data);
          ElMessage.success('编辑成功');
        } else {
          await createAttribute(data);
          ElMessage.success('新增成功');
        }
        
        dialogVisible.value = false;
        loadAttributeList();
      } catch (error) {
        console.error('保存属性失败:', error);
        ElMessage.error('保存属性失败');
      }
    }
  });
};

// 显示标签输入框
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    inputRef.value?.focus();
  });
};

// 处理标签输入确认
const handleInputConfirm = () => {
  if (inputValue.value) {
    if (!attributeForm.valueArray.includes(inputValue.value)) {
      attributeForm.valueArray.push(inputValue.value);
    }
  }
  inputVisible.value = false;
  inputValue.value = '';
};

// 处理关闭标签
const handleCloseTag = (index: number) => {
  attributeForm.valueArray.splice(index, 1);
};

// 页面加载时获取数据
onMounted(() => {
  loadAttributeList();
});
</script>